<template>
  <div class="container">
    <!-- 顶部搜索栏 -->
    <div class="search">
      <el-input v-model="params.name" placeholder="请输入用户名" clearable></el-input>
      <el-select v-model="params.role" clearable placeholder="请选择角色">
        <el-option label="超级管理员" value="0" />
        <el-option label="歌曲管理员" value="1" />
      </el-select>
      <el-select v-model="params.status" clearable placeholder="请选择用户状态">
        <el-option label="正常" value="0" />
        <el-option label="封禁" value="1" />
      </el-select>
      <el-button type="primary" @click="findBySearch()">搜索</el-button>
      <el-button type="warning" @click="clearParams">清空</el-button>
      <el-button type="success" @click="addAdmin">新增</el-button>
    </div>
    <!-- table表格 -->
    <div class="table">
      <!-- 斑马纹:stripe; 当前行高亮:highlight-current-row    sortable:排序[默认升序] -->
      <el-table :data="adminData" stripe highlight-current-row style="width: 100%">
        <el-table-column prop="id" label="序号" sortable width="130" />
        <el-table-column prop="name" label="用户名" width="180" />
        <el-table-column prop="role" label="角色">
          <template #default="{ row }">
            <el-tag v-if="row.role === '0'" type="success">超级管理员</el-tag>
            <el-tag v-else-if="row.role === '1'" type="primary">歌曲管理员</el-tag>
            <el-tag v-else type="warning">角色未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="loginTime" label="登录时间" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="sts" label="账号状态" width="140">
          <template #default="{ row }">
            <el-switch v-model="row.sts" @change="updataStatus(row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="editAdmin(row)">编辑</el-button>
            <!-- <el-button type="danger" size="small">删除</el-button> -->
            <el-popconfirm
              title="你确定删除吗？"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="deleteAdmin(row)"
            >
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页器 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="params.pageNum"
        v-model:page-size="params.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="params.total"
        @size-change="findBySearch"
        @current-change="findBySearch"
      />
    </div>

    <!-- 弹窗啥的 -->
    <div class="dialog">
      <!-- 新增or修改 -->
      <el-dialog
        v-model="dialogFormVisible"
        :title="formData.id ? '修改管理员信息' : '新增管理员信息'"
        width="500px"
        @close="cancel"
      >
        <el-form ref="formRef" :model="formData" :rules="rules" :hide-required-asterisk="true">
          <el-form-item label="用户名" label-width="20%" prop="name"
            ><el-input v-model="formData.name" palceholder="请输入用户名" clearable
          /></el-form-item>
          <el-form-item label="密码" label-width="20%" prop="password">
            <el-input v-model="formData.password" placeholder="请输入密码" clearable></el-input>
          </el-form-item>
          <el-form-item label="角色" label-width="20%" prop="role"
            ><el-select v-model="formData.role" placeholder="请选择" clearable>
              <el-option label="超级管理员" value="0"></el-option>
              <el-option label="歌曲管理员" value="1"></el-option> </el-select
          ></el-form-item>
          <el-form-item label="账号状态" label-width="20%" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio value="0">正常</el-radio>
              <el-radio value="1">封禁</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="confirm"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { adminDeleteApi, adminFindBySearchApi, adminSaveApi } from '@/api/admin'
import { getAdminName } from '@/utils/admin'
import { ElMessage } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

// 控制弹窗的隐藏与显示
const dialogFormVisible = ref(false)

// 获取当前管理员name
const adminName = getAdminName()

// 页面数据
const params = ref({
  name: '',
  role: '',
  status: '',
  pageNum: 1,
  pageSize: 10,
  total: '',
})
// 管理员数据
const adminData = ref([])
// 表单数据
const formData = reactive({
  id: '',
  name: '',
  role: '',
  status: '',
  password: '',
})
// 表单实例对象
const formRef = ref()
// 表单校验规则
const rules = {
  name: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  role: [{ required: true, message: '请选择用户角色', trigger: 'blur' }],
  status: [{ required: true, message: '请选择用户状态', trigger: 'blur' }],
}

onMounted(() => {
  findBySearch()
})

const findBySearch = async () => {
  let res = await adminFindBySearchApi(params.value)
  // console.log("res:", res)
  params.value.total = res.data.total

  // 修改返回数据中的sts
  const temp = res.data.list.map((item: any) => ({
    ...item,
    sts: item.status === '0',
  }))
  // Object.assign不是全部替换,而是把有的覆盖掉
  // 原因:当pageSize由大变小时不起作用
  // Object.assign(adminData,temp)
  // 此处解决方案:adminData由reactive==>ref
  adminData.value = temp
  // console.log(adminData.value)
}

// 初始化params[清空]
const clearParams = () => {
  ;(params.value.name = ''),
    (params.value.role = ''),
    (params.value.status = ''),
    (params.value.pageSize = 10),
    (params.value.pageNum = 1),
    (params.value.total = ''),
    // 清空之后还需再次请求数据
    findBySearch()
}
// 新增管理员
const addAdmin = () => {
  dialogFormVisible.value = true
}
// 删除管理员
const deleteAdmin = async (row: any) => {
  if (adminName === row.name) {
    ElMessage.error('不能删除自己')
  } else {
    await adminDeleteApi(row.id)
    ElMessage.success('删除成功')
    // 重新渲染
    findBySearch()
  }
}
// 编辑管理员
const editAdmin = (row: any) => {
  dialogFormVisible.value = true
  // console.log('编辑的管理员信息：',row)
  // formData.name = row.name
  // formData.password = row.password
  // formData.role = row.role
  // formData.status = row.status

  Object.keys(formData).forEach((key) => {
    // 此处断言为：告诉TS这里的key一定是formData所有键之一
    // console.log(key, ':', formData[key as keyof typeof formData])
    formData[key as keyof typeof formData] = row[key]
  })
}
// 修改管理员状态
const updataStatus = async (row: any) => {
  if (adminName === row.name) {
    row.sts = !row.sts
    ElMessage.error('不能操作自己')
  } else {
    row.status = row.status === '0' ? '1' : '0'
    await adminSaveApi(row)
    ElMessage.success('修改状态成功')
    findBySearch()
  }
}
// 清空表单数据
const clearFormData = () => {
  ;(formData.name = ''), (formData.password = ''), (formData.role = ''), (formData.status = ''), (formData.id = '')
}
// 弹窗确定
const confirm = async () => {
  await formRef.value.validate()
  await adminSaveApi(formData)
  ElMessage.success(formData.id ? '修改成功' : '添加成功')
  // 清空表单数据
  clearFormData()
  // 关闭弹窗
  dialogFormVisible.value = false
  // 重新渲染数据
  findBySearch()
}
// 弹窗取消
const cancel = () => {
  // 关闭弹窗
  dialogFormVisible.value = false
  // 清空表单数据
  clearFormData()
}
</script>

<style scoped lang="scss">
.container {
  .search {
    display: flex;
    flex-wrap: nowrap;

    .el-input,
    .el-select {
      width: 200px;
      margin-right: 10px;
    }
  }

  .table {
    margin: 15px 0;
    max-height: 76vh;
    overflow: auto;

    .el-switch {
      --el-switch-on-color: #13ce66;
      --el-switch-off-color: #ff4949;
    }
  }

  .pagination {
    margin-top: 30px;
    display: flex;
    justify-content: center;
  }

  .dialog {
    .el-input,
    .el-select {
      width: 90%;
    }
  }
}
</style>
